package controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ABCServlet
 */
@WebServlet("/ABCServlet")
public class ABCServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

		    private static final String CORRECT_USERNAME = "admin";
		    private static final String CORRECT_PASSWORD = "123456";
	
	public ABCServlet() {
		super();

		
	}

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());

	
    }

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
		
		request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String sessionControl = request.getParameter("session");
        String scope = request.getParameter("scope");
        if (CORRECT_USERNAME.equals(username) && CORRECT_PASSWORD.equals(password)) {
            Cookie usernameCookie = new Cookie("username", username);

            System.out.println("Cookies的 username 已设置：" + username);
            if ("persistent".equals(sessionControl)) {
                usernameCookie.setMaxAge(60);
            } else if ("delete".equals(sessionControl)) {
                usernameCookie.setMaxAge(0);
            } else {
                usernameCookie.setMaxAge(-1);
            }
            System.out.println("Cookies的过期时间已设置：" + sessionControl);
            if ("current".equals(scope)) {
                usernameCookie.setPath(request.getContextPath());
            } else if ("root".equals(scope)) {
                usernameCookie.setPath("/");
            } else if ("domain".equals(scope)) {
                usernameCookie.setDomain(request.getServerName());
            }
            System.out.println("Cookies的生效范围已设置：" + scope);
            response.addCookie(usernameCookie);
            response.sendRedirect("welcome.jsp");
        } else {
    	    System.out.println("用户登录失败，登录用户名：" + username + "，登录密码：" + password);
            response.getWriter().println("<script>alert('用户名或密码错误！');window.location.href='login.jsp';</script>");
        }
		
		
	}

}
